package com.neo.androidcommon.retrofitDemo.net;

import android.util.Log;

import com.neo.androidcommon.retrofitDemo.constant.Constant;
import com.neo.androidcommon.retrofitDemo.entity.BaseInfoBean;
import com.neo.androidcommon.retrofitDemo.impl.RetrofitService;
import com.neo.androidcommon.retrofitDemo.manger.ReceiveMessageManager;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/10/16.
 */

public class HttpChannel {

    private static HttpChannel httpChannel;
    private final RetrofitService service;

    public static HttpChannel getInstance() {

        return httpChannel == null ? httpChannel = new HttpChannel() : httpChannel;

    }

    private HttpChannel() {

        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl(Constant.SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(RetrofitUtils.getOkHttpClient())
                .build();
        service = retrofit.create(RetrofitService.class);

    }


    public RetrofitService getService() {
        return service;
    }
    /**
     * 发送消息
     *
     * @param observable Observable<? extends BaseBean>
     * @param urlOrigin  请求地址
     */
    public void sendMessage(Observable<? extends BaseInfoBean> observable, final String urlOrigin) {

                observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BaseInfoBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(BaseInfoBean value) {
                                Log.i("http返回：", value.toString() + "");
                                ReceiveMessageManager.getInstance().dispatchMessage(value, urlOrigin);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });



    }


}
